﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace Common
{
    public class Tool
    {
        /// <summary>
        /// Tool.AutoCopy<父类型（原有）, 子类型（被赋值）>(父对象);
        /// </summary>
        /// <typeparam name="TParent">父类型（原有）</typeparam>
        /// <typeparam name="TChild">子类型（被赋值）</typeparam>
        /// <param name="parent">父对象</param>
        /// <returns></returns>
        public static TChild AutoCopy<TParent, TChild>(TParent parent) where TChild : TParent, new()
        {
            TChild child = new TChild();
            var ParentType = typeof(TParent);
            var Properties = ParentType.GetProperties();
            foreach (var Propertie in Properties)
            {
                //循环遍历属性
                if (Propertie.CanRead && Propertie.CanWrite)
                {
                    //进行属性拷贝
                    Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
                }
            }
            return child;
        }

        /// <summary>
        /// list转成table，要确保list的类型一致，尽量都变成string
        /// </summary>
        /// <returns></returns>
        public static DataTable listToTable<T>(List<T> entitys)
        {
            if (entitys == null || entitys.Count < 1)
            {
                return new DataTable();
            }

            Type entityType = entitys[0].GetType();
            PropertyInfo[] entitysPropertyInfos = entityType.GetProperties();
            var dt = new DataTable("dt");
            for (int i = 0; i < entitysPropertyInfos.Length; i++)
            {
                dt.Columns.Add(entitysPropertyInfos[i].Name);
            }

            foreach (var entity in entitys)
            {
                if (entity.GetType() != entityType)
                {
                    throw new Exception("集合元素类型不一致");
                }
                object[] entityValues = new object[entitysPropertyInfos.Length];
                for (int i = 0; i < entitysPropertyInfos.Length; i++)
                {
                    entityValues[i] = entitysPropertyInfos[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }
    }
}